#!/usr/bin/env python
import pika
import time

"""
两个消费者会, 轮流消费消息, 

确保每次只处理一个消息
"""

credentials = pika.PlainCredentials(username='chf', password='123456')  # mq用户名和密码
connection = pika.BlockingConnection(pika.ConnectionParameters(host='117.72.79.182', port=5672, credentials=credentials))
channel = connection.channel()

channel.queue_declare(queue='task_queue', durable=True)
print(' [*] Waiting for messages. To exit press CTRL+C')


def callback(ch, method, properties, body):
    print(f" [{time.time()}] Received {body.decode()}")
    time.sleep(body.count(b'.'))
    print(" [x] Done")
    ch.basic_ack(delivery_tag=method.delivery_tag)


channel.basic_qos(prefetch_count=2) # 确保每次只处理一个消息
channel.basic_consume(queue='task_queue', on_message_callback=callback)

channel.start_consuming()